﻿Imports System.ComponentModel.Composition
Imports System.ComponentModel.Composition.Hosting
Imports System.Reflection
Imports System.Text
Imports SFDL.Logging
Imports System.ComponentModel
Imports SFDL.PluginInterfaces

<Export(GetType(ISFDLLoaderPlugin))>
Public Class PluginConnector

    Private Shared _plugin_container As CompositionContainer
    Private Shared _plugin_catalog As New AggregateCatalog
    Private Shared _log As NLog.Logger = NLog.LogManager.GetLogger("PluginConnector")

    <ImportMany()>
    Public CustomCommandPlugins As ICustomCommandPlugin()
    <ImportMany()>
    Public ClicknLoadPlugins As IClicknLoadPlugin()
    <ImportMany()>
    Public PostUnRARPlugins As IPostUnRARPlugin()

    Public Sub LoadPlugins(ByVal _plugindir As String)

        Try


            For Each _plugin_update In IO.Directory.GetFiles(_plugindir, "*.delete")
                IO.File.Delete(_plugin_update.Replace(".delete", ""))
                IO.File.Delete(_plugin_update)
            Next

            For Each _plugin_update In IO.Directory.GetFiles(_plugindir, "*.new")
                IO.File.Move(_plugin_update, _plugin_update.Replace(".new", ""))
            Next


            For Each _plugin In IO.Directory.GetFiles(_plugindir, "*.dll")

                Try

                    _log.Info("Versuche Plugin {0} zu laden...", IO.Path.GetFileNameWithoutExtension(_plugin))

                    Dim _assembly As Assembly
                    Dim _assembly_catalog As AssemblyCatalog
                    Dim _parts() As Object

                    If IO.File.Exists(_plugin & ".disabled") Then
                        Throw New PluginDisabledException("Plugin ist deaktiviert und wird daher nicht geladen!")
                    End If

                    _assembly = Assembly.UnsafeLoadFrom(_plugin)

                    _assembly_catalog = New AssemblyCatalog(_assembly)

                    _parts = _assembly_catalog.Parts.ToArray

                    _plugin_catalog.Catalogs.Add(_assembly_catalog)

                    _log.Info("OK - Plugin geladen")

                Catch ex As PluginDisabledException

                    _log.Info(ex, ex.Message)

                Catch ex As Reflection.ReflectionTypeLoadException

                    Dim _ex_string As New StringBuilder

                    For Each e In ex.LoaderExceptions
                        _ex_string.AppendLine(e.Message)
                    Next

                    _log.Error(ex, _ex_string.ToString)

                End Try

            Next

            _log.Info("Baue nun alles zusammen...")

            _plugin_container = New CompositionContainer(_plugin_catalog)
            _plugin_container.ComposeParts(Me)

            _log.Info("Fertig!")

        Catch ex As Exception
            _log.Error(ex, ex.Message)
        End Try

    End Sub

End Class
